package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.service.impl.EmailSerivce;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailSerivce emailSerivce;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            //调用阿里云提供的短信服务API完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖付哥版",phone,code);
            //使用网易邮箱发送验证码
            //boolean b = emailSerivce.sendEmailCode(code, "chujiua2022@163.com", "535174754@qq.com");
            //需要将生成的验证码保存到Session
            //session.setAttribute(phone,code);
            //短信防刷
            String keyCode = "msg_" + user.getPhone();
            Long recordTime = (Long) redisTemplate.opsForValue().get(keyCode);
            if ( recordTime!= null) {
                if ((System.currentTimeMillis() - recordTime)/1000 <= 30) {
                    throw new CustomException("请"+(30 - (System.currentTimeMillis()-recordTime)/1000)+"秒后再发送");
                }
            }
            //记录发送验证码时间
            redisTemplate.opsForValue().set(keyCode,System.currentTimeMillis(),30,TimeUnit.SECONDS);

            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            log.info(code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//使用redis缓存验证码
            return R.success("发送验证码成功");
        }
        return R.error("短信发送失败");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {
        log.info(map.toString());
        //获取手机号
        String phone = (String) map.get("phone");
        //获取验证码
        String inputCode = (String) map.get("code");
        //String code = (String) session.getAttribute(phone);
        //从redis获取验证码
        String code = (String) redisTemplate.opsForValue().get(phone);
        if (code == null) {
            throw new CustomException("验证码已过期");
        }
        //进行验证码的比对(页面提交的验证码与Session中比较)
        if (!(code!=null && code.equals(inputCode))) {
            return R.error("登录失败！");
        }
        //判断当前登录用户是否为新用户
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(phone != null, User::getPhone, phone));
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        //登录成功删除缓存中的验证码
        redisTemplate.delete(phone);
        return R.success(user);
    }
    @PostMapping("/loginout")
    public R loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success(null);
    }

}
